<template>
  <div class="container">
    <!-- 左侧区域 -->
    <div class="left-panel">
      <div class="search-bar">
        <input
            v-model="searchText"
            type="text"
            placeholder="搜索..."
            class="search-input"
        />
        <button class="search-button" @click="fetchChatHistory">搜索</button>
      </div>
      <div class="card-container">
        <div
            v-for="(card, index) in filteredCards"
            :key="index"
            class="card"
            @click="selectChat(card.chatId)"
            style="line-height: 14px"
        >
          <div class="card-header">
            <img :src="card.chatWithAvatarUrl" class="avatar" v-if="card.chatWithAvatarUrl"/>
            <div class="receiver-info">
              <div class="receiver-name">{{ card.chatWith }}</div>
              <div class="send-time">{{ formatTime(card.sendTime) }}</div>
            </div>
          </div>
          <div class="message-preview">{{ truncateContent(card.messageContent) }}</div>
        </div>
      </div>
    </div>

    <!-- 右侧区域 -->
    <div class="right-panel">
      <div class="chat-header" v-if="selectedChatId">
        <el-avatar :src="receiverAvatarUrl" class="avatar"/>
        <span class="chat-with-name">{{ currentReceiverName }}</span>
      </div>
      <div class="right-top">
        <div class="content-display">
          <div v-for="(message, index) in messages" :key="index" class="message"
               :class="{ 'sender-message': message.senderId === userId,
                         'receiver-message': message.senderId !== userId }">
            <div class="message-content-wrapper">
              <el-avatar :src="message.senderId === userId ? senderAvatarUrl : receiverAvatarUrl" class="avatar"
                   v-if="senderAvatarUrl || receiverAvatarUrl"/>
              <div class="message-bubble">
                <div class="sender-name">{{ message.senderName }} {{ message.sendTime }}</div>
                <div class="bubble-content">{{ message.messageContent }}</div>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="right-bottom">
        <textarea
            v-model="inputMessage"
            type="text"
            placeholder="输入消息..."
            class="message-input"
        />
        <button class="clear-button" @click="clearMessage">清空</button>
        <button class="send-button" @click="sendPrivateMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, computed, onMounted, onUnmounted} from 'vue';
import axios from 'axios';
import {Client} from '@stomp/stompjs';
import SockJS from 'sockjs-client';
import {ElMessage} from "element-plus";
import {notify} from "@kyvg/vue3-notification";

// 接收者名称
const currentReceiverName = ref('');

// 用户的所有聊天chatIds
const chatIds = ref([]);

// 左侧卡片数据
const cards = ref([]);
const userId = ref(parseInt(localStorage.getItem('id'))); // 从localStorage获取当前用户ID
const userName = ref(localStorage.getItem('username')); // 从localStorage获取当前用户名
const searchText = ref('');
const selectedChatId = ref(null); // 当前选中的聊天ID
const messages = ref([]); // 当前聊天的消息列表
const inputMessage = ref('');

// 头像
const senderAvatarUrl = ref('');
const receiverAvatarUrl = ref('');

// 过滤卡片
const filteredCards = computed(() => {
  if (!searchText.value) return cards.value;
  return cards.value.filter(card =>
      card.receiverName.toLowerCase().includes(searchText.value.toLowerCase()) ||
      card.messageContent.toLowerCase().includes(searchText.value.toLowerCase())
  );
});

// 获取聊天列表
const fetchChatHistory = async () => {
  try {
    const response = await axios.get(`/chat/historyList/${userId.value}`);
    cards.value = response.data.data || [];
    console.log(cards.value)
  } catch (error) {
    console.error('获取聊天列表失败:', error);
  }
};

// 根据chatId获取聊天历史记录
const fetchChatMessages = async (chatId) => {
  try {
    const response = await axios.get(`/chat/history/chatId?chatId=${chatId}`);
    messages.value = response.data.data || [];
    //获取两者的头像
    const arr = chatId.split('_').map(Number);
    for (let i = 0; i < 2; i++) {
      const response_avatar = await axios.get('/user/getAvatar/' + arr[i])
      if (parseInt(localStorage.getItem('id')) === arr[i]) {
        senderAvatarUrl.value = response_avatar.data.data;
      } else {
        receiverAvatarUrl.value = response_avatar.data.data;
      }
    }
  } catch (error) {
    console.error('获取聊天历史记录失败:', error);
  }
};

// 格式化时间显示
const formatTime = (time) => {
  if (!time) return '';
  const now = new Date();
  const date = new Date(time);

  if (date.toDateString() === now.toDateString()) {
    return date.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'});
  }

  const yesterday = new Date(now);
  yesterday.setDate(yesterday.getDate() - 1);
  if (date.toDateString() === yesterday.toDateString()) {
    return '昨天';
  }

  return date.toLocaleDateString();
};

// 截断过长的消息内容
const truncateContent = (content) => {
  if (!content) return '';
  return content.length > 30 ? content.substring(0, 30) + '...' : content;
};

// 选择聊天
const selectChat = (chatId) => {
  selectedChatId.value = chatId;
  // 从卡片数据中查找对应的聊天
  const selectedCard = cards.value.find(card => card.chatId === chatId);
  if (selectedCard) {
    // 设置接收者名称
    currentReceiverName.value = selectedCard.chatWith;
  }
  fetchChatMessages(chatId).then(() => {
    // 滚动到消息列表的底部
    const contentDisplay = document.querySelector('.content-display');
    if (contentDisplay) {
      contentDisplay.scrollTop = contentDisplay.scrollHeight;
    }
  });
};

// 清空消息
const clearMessage = () => {
  inputMessage.value = '';
};

//websocket相关
// 连接WebSocket - 创建连接对象
const socket = new SockJS('http://121.199.30.8:9937/ws')
const stompClient = new Client({
  webSocketFactory: () => socket,
  debug: function (str) {
    console.log(str);
  }
})

// 进行连接
stompClient.onConnect = (frame) => {
  console.log('连接成功: ' + frame);

  fetchChatIds().then(() => {
    subscribeToChats();
  })
}
stompClient.activate();

//订阅消息
//先获取当前用户的所有聊天
const fetchChatIds = async () => {
  try {
    const response = await axios.get('/chat/getChatIds/' + userId.value);
    chatIds.value = response.data.data || [];
    console.log(chatIds.value)
  } catch (error) {
    ElMessage.error('获取聊天列表失败:', error);
  }
}

// 订阅所有聊天
const subscribeToChats = () => {
  chatIds.value.forEach(chatId => {
    stompClient.subscribe(`/queue/private/${chatId}`, (message) => {
      const receivedMessage = JSON.parse(message.body);
      console.log(receivedMessage)
      console.log('收到消息，路径:', message.headers.destination);
      console.log('消息内容:', message.body);
      if (receivedMessage.senderId !== userId.value) {
        notify({
          title: "收到来自" + receivedMessage.senderName + "的1条消息",
          text: receivedMessage.messageContent,
          type: 'success',
          duration: 5000,
        })
      }

      // 如果是当前聊天，则添加到消息列表
      if (selectedChatId.value === receivedMessage.chatId) {
        messages.value.push(receivedMessage);
      }

      // 显示桌面通知
      if (Notification.permission === 'granted' && receivedMessage.senderId !== userId.value) {
        new Notification(`${receivedMessage.senderName}`, {
          body: receivedMessage.messageContent
        });
      }

      // 更新左侧卡片列表
      updateCardList(receivedMessage);
    })
  })
}

// 更新左侧卡片列表
const updateCardList = (message) => {
  const chatId = message.chatId;
  const chatWith = message.senderId === userId.value ? message.receiverName : message.senderName;
  const chatWithAvatarUrl = message.senderId === userId.value ? receiverAvatarUrl.value : senderAvatarUrl.value;

  const existingCardIndex = cards.value.findIndex(card => card.chatId === chatId);

  if (existingCardIndex !== -1) {
    // 更新现有卡片
    cards.value[existingCardIndex] = {
      ...cards.value[existingCardIndex],
      messageContent: message.messageContent,
      sendTime: message.sendTime
    };
  } else {
    // 添加新卡片
    cards.value.unshift({
      chatId,
      chatWith,
      chatWithAvatarUrl,
      messageContent: message.messageContent,
      sendTime: message.sendTime
    });
  }

  // 按时间排序
  cards.value.sort((a, b) => new Date(b.sendTime) - new Date(a.sendTime));

  // 如果是当前聊天，则滚动到底部
  if (selectedChatId.value === message.chatId) {
    setTimeout(() => {
      const contentDisplay = document.querySelector('.content-display');
      if (contentDisplay) {
        contentDisplay.scrollTop = contentDisplay.scrollHeight;
      }
    }, 0);
  }
}

//发送私聊信息
const sendPrivateMessage = () => {
  if (!inputMessage.value.trim()) return;
  if (!selectedChatId.value) {
    ElMessage.warning('请先选择聊天');
    return;
  }

  // 解析聊天ID获取对方ID
  const arr = selectedChatId.value.split('_').map(Number);
  const receiverId = arr[0] === userId.value ? arr[1] : arr[0];

  // 创建本地消息对象
  const newMessage = {
    chatId: selectedChatId.value,
    senderId: userId.value,
    senderName: userName.value,
    receiverId: receiverId,
    receiverName: currentReceiverName.value,
    messageContent: inputMessage.value,
    sendTime: new Date().toISOString()
  };

  // // 立即添加到消息列表
  // messages.value.push(newMessage);

  // 更新左侧卡片
  updateCardList(newMessage);

  // 通过WebSocket发送
  stompClient.publish({
    destination: `/app/sendMessage`,
    body: JSON.stringify(newMessage),
  });

  // 清空输入框
  inputMessage.value = '';

  // 滚动到底部
  setTimeout(() => {
    const contentDisplay = document.querySelector('.content-display');
    if (contentDisplay) {
      contentDisplay.scrollTop = contentDisplay.scrollHeight;
    }
  }, 0);
}

// 组件挂载时获取数据
onMounted(() => {
  fetchChatHistory();
  stompClient.activate();
});

// 组件卸载时断开连接
onUnmounted(() => {

});
</script>

<style scoped>
.container {
  display: flex;
  height: 100vh;
  width: 100%;
}

.left-panel {
  width: 20%;
  height: 100%;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #ddd;
  background-color: #f5f5f5;
}

.search-bar {
  padding: 10px;
  display: flex;
  gap: 5px;
  border-bottom: 1px solid #ddd;
  background-color: white;
}

.search-input {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.search-button {
  padding: 8px 12px;
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.search-button:hover {
  background-color: #45a049;
}

.card-container {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.card {
  padding: 8px;
  margin-bottom: 8px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  cursor: pointer;
  transition: all 0.2s ease;
}

.card:hover {
  background-color: #f0f0f0;
  transform: translateY(-2px);
}

.card-header {
  display: flex;
  align-items: center;
  margin-bottom: 4px;
}

.avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  margin-right: 12px;
  object-fit: cover;
}

.receiver-info {
  flex: 1;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.receiver-name {
  font-weight: bold;
  font-size: 14px;
  margin-right: 8px;
}

.send-time {
  font-size: 12px;
  color: #888;
  white-space: nowrap;
}

.message-preview {
  font-size: 13px;
  color: #666;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-left: 60px;
  text-align: left;
}

.right-panel {
  width: 80%;
  height: 100%;
  display: flex;
  flex-direction: column;
  /* 添加以下两行确保内容区域可以伸缩 */
  min-height: 0; /* 重要：允许内容区域收缩 */
}

.right-top {
  flex: 1; /* 占据剩余所有空间 */
  min-height: 0; /* 重要：允许内容区域收缩 */
  overflow-y: auto; /* 保持可滚动 */
  padding: 20px;
  background-color: white;
}

.right-bottom {
  /* 移除固定高度，改为由内容自动撑开 */
  padding: 15px;
  display: flex;
  gap: 10px;
  align-items: center;
  border-top: 1px solid #ddd;
  background-color: #f9f9f9;
  /* 添加以下属性使输入框可以扩展 */
  flex-shrink: 0; /* 防止压缩 */
}

.message-input {
  /* 让输入框可以自由扩展 */
  flex: 1;
  min-height: 140px; /* 最小高度 */
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  /* 支持多行文本 */
  resize: vertical; /* 允许垂直调整大小 */
  overflow-y: auto; /* 内容过多时显示滚动条 */
}

.clear-button {
  padding: 10px 15px;
  background-color: #f44336;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.clear-button:hover {
  background-color: #d32f2f;
}

.send-button {
  padding: 10px 15px;
  background-color: #2196f3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.send-button:hover {
  background-color: #0b7dda;
}

.content-display {
  height: 100%;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.message {
  display: flex;
  max-width: 80%;
}

.sender-message {
  align-self: flex-end;
  justify-content: flex-end;
}

.receiver-message {
  align-self: flex-start;
  justify-content: flex-start;
}

.message-content-wrapper {
  display: flex;
  align-items: flex-end;
  gap: 8px;
  max-width: 100%;
}

.sender-message .message-content-wrapper {
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  object-fit: cover;
  flex-shrink: 0;
}

.message-bubble {
  display: flex;
  flex-direction: column;
  max-width: 100%;
}

.sender-name {
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
  padding: 0 4px;
  line-height: 1.2;
}

.sender-message .sender-name {
  text-align: right;
}

.receiver-message .sender-name {
  text-align: left;
}

.bubble-content {
  padding: 8px 12px;
  border-radius: 12px;
  word-wrap: break-word;
  line-height: 1.4;
  max-width: 100%;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
}

.sender-message .bubble-content {
  background-color: #d4edda;
  color: #155724;
  border-bottom-right-radius: 2px;
}

.receiver-message .bubble-content {
  background-color: #e2e3e5;
  color: #383d41;
  border-bottom-left-radius: 2px;
}

.chat-header {
  padding: 10px;
  border-bottom: 1px solid #ddd;
  display: flex;
  align-items: center;
  gap: 10px;
  background-color: #f9f9f9;
}

.chat-with-name {
  font-weight: bold;
  font-size: 16px;
  line-height: 1.2;
}

/* 暗黑模式下的样式 */
[data-theme="dark"] .container {
  background-color: #121212;
  color: #fff;
}

[data-theme="dark"] .left-panel {
  background-color: #1e1e1e;
  border-right: 1px solid #333;
}

[data-theme="dark"] .search-bar {
  background-color: black;
  border-bottom: 1px solid #333;
}

[data-theme="dark"] .search-input {
  background-color: #333;
  border: 1px solid #444;
  color: #fff;
}

[data-theme="dark"] .search-button {
  background-color: #4caf50;
  color: white;
}

[data-theme="dark"] .search-button:hover {
  background-color: #45a049;
}

[data-theme="dark"] .card {
  background-color: #282828;
  border: 1px solid #333;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
}

[data-theme="dark"] .card-container {
  background-color: black;
}

[data-theme="dark"] .card:hover {
  background-color: #333;
}

[data-theme="dark"] .receiver-name {
  color: #fff;
}

[data-theme="dark"] .send-time {
  color: #777;
}

[data-theme="dark"] .message-preview {
  color: #777;
}

[data-theme="dark"] .right-panel {
  background-color: black;
}

[data-theme="dark"] .right-top {
  background-color: black;
}

[data-theme="dark"] .right-bottom {
  background-color: #282828;
  border-top: 1px solid #333;
}

[data-theme="dark"] .message-input {
  background-color: #333;
  border: 1px solid #444;
  color: #fff;
}

[data-theme="dark"] .clear-button {
  background-color: #f44336;
  color: white;
}

[data-theme="dark"] .clear-button:hover {
  background-color: #d32f2f;
}

[data-theme="dark"] .send-button {
  background-color: #2196f3;
  color: white;
}

[data-theme="dark"] .send-button:hover {
  background-color: #0b7dda;
}

[data-theme="dark"] .sender-message .bubble-content {
  background-color: #007b00;
  color: #d4edda;
}

[data-theme="dark"] .receiver-message .bubble-content {
  background-color: #444;
  color: #e2e3e5;
}

[data-theme="dark"] .chat-header {
  background-color: black;
  border-bottom: 1px solid #333;
}

[data-theme="dark"] .chat-with-name {
  color: #fff;
}

[data-theme="dark"] .sender-name {
  color: #777;
}

[data-theme="dark"] .message-preview {
  color: #fff;
}

[data-theme="dark"] .sender-name {
  color: #fff;
}

/* 添加过渡效果 */
[data-theme="dark"],
[data-theme="light"] {
  transition: background-color 0.3s, color 0.3s, border-color 0.3s; /* 添加过渡效果 */
}
</style>